package com.zsgeek.wisdchain.qutu;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OSUtils;
import com.lzy.okgo.OkGo;
import com.zsgeek.wisdchain.qutu.base.event.BaseEvent;
import com.zsgeek.wisdchain.qutu.base.event.BaseEventBusHelper;
import com.zsgeek.wisdchain.qutu.base.presenter.BaseContract;
import com.zsgeek.wisdchain.qutu.base.setLanguage.LocalManageUtil;
import com.zsgeek.wisdchain.qutu.tools.LogUtil;
import com.zsgeek.wisdchain.qutu.tools.ToastHelper;
import com.zsgeek.wisdchain.qutu.tools.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity<T extends BaseContract.BasePresenter> extends AppCompatActivity implements BaseContract.BaseView {
    private Unbinder mUnbinder;
    //    protected T mPresenter;
    protected ImmersionBar mImmersionBar;
    protected Toolbar mToolbar;
    protected Button btnRight;

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocalManageUtil.setLocal(newBase));
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(getLayoutId());


        mToolbar = findViewById(R.id.toolbar);
        if (mToolbar != null) {
            setTitle("");
            mToolbar.setNavigationOnClickListener(v -> onBackPressed());
        }
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }

        mUnbinder = ButterKnife.bind(this);
//        mPresenter = initPresenter();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView();
        initDate(savedInstanceState);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this.getClass());
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BaseEvent event) {
        if (event.getEvent() == BaseEventBusHelper.EVENT_LOGOUT) {
            getParent().finish();
        }
    }


    @Override
    public void setTitle(CharSequence title) {
//        if (mToolbar == null) {
//            super.setTitle(title);
//            return;
//        }
//        super.setTitle("");
        if (!TextUtils.isEmpty(title)) {
            TextView tvTitle = mToolbar.findViewById(R.id.toolbar_title);
            tvTitle.setText(title);
        }
    }

    protected void setToolbarRight(String text, @Nullable Integer icon, int width, int height, View.OnClickListener btnClick) {
        btnRight = mToolbar.findViewById(R.id.btnRight);
        if (btnRight != null) {
            if (text != null) {
                btnRight.setText(text);
            }
            if (icon != null && icon > 0) {
                btnRight.setBackgroundResource(icon.intValue());
                ViewGroup.LayoutParams linearParams = btnRight.getLayoutParams();
                linearParams.width = Utils.Dp2Px(this, width);
                linearParams.height = Utils.Dp2Px(this, height);
                btnRight.setLayoutParams(linearParams);
            }
            btnRight.setOnClickListener(btnClick);
        }
    }

    @Override
    public void showError(String msg) {
        ToastHelper.showToast(msg);
    }

    @Override
    public void showLoading(String msg) {
    }

    @Override
    public void hideLoading() {
    }

    @LayoutRes
    public abstract int getLayoutId();

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    protected abstract void initView();

    protected abstract void initDate(Bundle savedInstanceState);

    protected boolean isDarkStatusBar() {
        return true;
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        if (ImmersionBar.isSupportStatusBarDarkFont()) {    //判断当前设备支不支持状态栏字体变色
            mImmersionBar.statusBarDarkFont(isDarkStatusBar());
        } else LogUtil.e("当前设备支不支持状态栏字体变色");
        if (mToolbar != null)
            mImmersionBar.titleBar(mToolbar);
        mImmersionBar.init();
    }

//    private T initPresenter() {
//        return null;
//    }

    @Override
    protected void onResume() {
        super.onResume();
        // 非必加
        // 如果你的app可以横竖屏切换，适配了华为emui3系列系统手机，并且navigationBarWithEMUI3Enable为true，
        // 请在onResume方法里添加这句代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、华为emui3系列系统手机；3、navigationBarWithEMUI3Enable为true）
        // 否则请忽略
        if (OSUtils.isEMUI3_x() && isImmersionBarEnabled()) {
            mImmersionBar.init();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mImmersionBar != null || isImmersionBarEnabled()) {
            mImmersionBar.destroy();
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        OkGo.getInstance().cancelAll();
    }
}
